﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Database.Context;
using QuanLyThongTinCoSo.Common;
using Model = Database.Models;

namespace QuanLyThongTinCoSo.Biz
{
    public class CanBoQuanLyBiz : BaseBiz
    {
        public CanBoQuanLyBiz()
        {
            DbContext = new Context();
        }

        public CanBoQuanLyBiz(Context context)
        {
            DbContext = context;
        }

        public override void Insert(Model.BaseModel model)
        {
            var canBo = model as Model.CanBo;
            canBo.Created = DateTime.Now;
            canBo.Modified = DateTime.Now;
            canBo.CreatedBy = Utilities.CurrentUser();
            canBo.ModifiedBy = Utilities.CurrentUser();

            DbContext.CanBoQuanLies.Add(canBo);
            DbContext.SaveChanges();
        }

        public override void Update(Model.BaseModel model)
        {
            var canBo = model as Model.CanBo;
            canBo.Modified = DateTime.Now;
            canBo.ModifiedBy = Utilities.CurrentUser();

            DbContext.Entry(canBo).State = EntityState.Modified;
            DbContext.SaveChanges();
        }

        public override void Delete(Model.BaseModel model)
        {
            DbContext.CanBoQuanLies.Attach(model as Model.CanBo);
            DbContext.CanBoQuanLies.Remove(model as Model.CanBo);
            DbContext.Entry(model).State = EntityState.Deleted;

            DbContext.SaveChanges();
        }

        public override void DeleteItems(List<Model.BaseModel> models)
        {
            foreach (Model.CanBo canBo in models)
            {
                DbContext.CanBoQuanLies.Attach(canBo);
                DbContext.CanBoQuanLies.Remove(canBo);
                DbContext.Entry(canBo).State = EntityState.Deleted;
            }

            DbContext.SaveChanges();
        }

        public override Model.BaseModel GetItemById(int id)
        {
            return (from item in DbContext.CanBoQuanLies
                    where item.Id == id
                    select item).First();
        }

        public Model.CanBo GetRoleByName(string ten)
        {
            return DbContext.CanBoQuanLies.FirstOrDefault(c => c.HoTen == ten);
        }

        public List<Model.CanBo> GetAll()
        {
            return DbContext.CanBoQuanLies.OrderBy(c => c.HoTen).ToList();
        }

        public List<Model.CanBo> GetAllAvailable()
        {
            return DbContext.CanBoQuanLies.Where(c => c.Doi == null).OrderBy(c => c.HoTen).ToList();
        }
    }
}